<template>
  <div class="word-timestamp-viewer">
    <div class="flex items-center justify-between mb-4">
      <h3 class="text-lg font-semibold text-gray-900">详细转录</h3>
      <div class="flex items-center gap-2">
        <button
          @click="toggleTimestamps"
          class="text-primary-600 hover:text-primary-700 text-sm px-3 py-1 rounded-lg hover:bg-primary-50 transition-colors"
        >
          {{ showTimestamps ? '隐藏时间戳' : '显示时间戳' }}
        </button>
        <button
          @click="exportWithTimestamps"
          class="text-gray-600 hover:text-gray-700 p-2 hover:bg-gray-50 rounded-lg transition-colors"
          title="导出带时间戳的文本"
        >
          <Download class="w-4 h-4" />
        </button>
      </div>
    </div>

    <div class="bg-gray-50 rounded-lg p-4">
      <!-- 基本转录文本 -->
      <div v-if="!showTimestamps" class="text-gray-900 leading-relaxed whitespace-pre-wrap">
        {{ transcription.text }}
      </div>

      <!-- 带时间戳的词级展示 -->
      <div v-else class="space-y-2">
        <div
          v-for="(word, index) in wordTimestamps"
          :key="index"
          class="inline-block"
          @mouseenter="hoveredWord = index"
          @mouseleave="hoveredWord = null"
        >
          <span
            class="px-1 py-0.5 rounded cursor-pointer transition-colors duration-200"
            :class="{
              'bg-blue-100 text-blue-800': hoveredWord === index,
              'bg-gray-100 text-gray-700': hoveredWord !== index
            }"
            @click="playSegment(word)"
          >
            {{ word.word }}
          </span>
        </div>
      </div>

      <!-- 词级时间戳列表 -->
      <div v-if="showTimestamps && wordTimestamps.length > 0" class="mt-6 border-t pt-4">
        <h4 class="text-sm font-medium text-gray-700 mb-3">词级时间戳</h4>
        <div class="max-h-40 overflow-y-auto space-y-1">
          <div
            v-for="(word, index) in wordTimestamps"
            :key="index"
            class="flex items-center justify-between text-sm py-1 px-2 rounded hover:bg-gray-100 transition-colors"
          >
            <span class="font-mono text-gray-900">{{ word.word }}</span>
            <span class="text-gray-500 font-mono">
              {{ formatTime(word.start || 0) }} - {{ formatTime(word.end || 0) }}
            </span>
          </div>
        </div>
      </div>

      <!-- 统计信息 -->
      <div class="mt-4 pt-4 border-t border-gray-200 flex items-center justify-between text-sm text-gray-600">
        <div class="flex items-center gap-4">
          <span>总词数: {{ transcription.word_count || 0 }}</span>
          <span>时长: {{ formatDuration(transcription.duration || 0) }}</span>
          <span>语言: {{ getLanguageName(transcription.language) }}</span>
        </div>
        <div class="flex items-center gap-2">
          <div class="w-2 h-2 rounded-full" :class="confidenceColor"></div>
          <span>置信度: {{ (transcription.confidence * 100).toFixed(1) }}%</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { Download } from 'lucide-vue-next'

interface WordTimestamp {
  word: string
  start?: number
  end?: number
}

interface Transcription {
  text: string
  confidence: number
  duration: number
  word_count: number
  word_timestamps: WordTimestamp[]
  language: string
  model: string
}

interface Props {
  transcription: Transcription
}

const props = defineProps<Props>()

const showTimestamps = ref(false)
const hoveredWord = ref<number | null>(null)

const wordTimestamps = computed(() => {
  const timestamps = props.transcription.word_timestamps || []

  if (timestamps.length === 0) {
    // 如果没有时间戳，根据文本分割生成简单的词级信息
    const words = props.transcription.text.split(/\s+/)
    return words.map((word, index) => ({
      word,
      start: index * 0.5,  // 假设每个词0.5秒
      end: (index + 1) * 0.5
    }))
  }

  return timestamps
})

const confidenceColor = computed(() => {
  const confidence = props.transcription.confidence
  if (confidence >= 0.9) return 'bg-green-500'
  if (confidence >= 0.7) return 'bg-yellow-500'
  return 'bg-red-500'
})

const toggleTimestamps = () => {
  showTimestamps.value = !showTimestamps.value
}

const playSegment = (word: WordTimestamp) => {
  // TODO: 实现音频播放功能，跳转到指定时间
  console.log(`播放片段: ${word.word} (${formatTime(word.start || 0)} - ${formatTime(word.end || 0)})`)
}

const exportWithTimestamps = () => {
  let content = ''

  if (showTimestamps.value && wordTimestamps.value.length > 0) {
    content = wordTimestamps.value
      .map(word => `[${formatTime(word.start || 0)}] ${word.word}`)
      .join(' ')
  } else {
    content = props.transcription.text
  }

  const blob = new Blob([content], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `transcription-${new Date().toISOString().split('T')[0]}.txt`
  a.click()
  URL.revokeObjectURL(url)
}

const formatTime = (seconds: number) => {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins.toString().padStart(2, '0')}:${secs.toFixed(2).padStart(5, '0')}`
}

const formatDuration = (seconds: number) => {
  const mins = Math.floor(seconds / 60)
  const secs = Math.floor(seconds % 60)
  return `${mins}:${secs.toString().padStart(2, '0')}`
}

const getLanguageName = (language: string) => {
  const languages: Record<string, string> = {
    'chinese': '中文',
    'english': 'English',
    'japanese': '日本語',
    'korean': '한국어',
    'auto': '自动检测'
  }
  return languages[language] || language
}
</script>

<style scoped>
.word-timestamp-viewer {
  /* 自定义滚动条样式 */
  .overflow-y-auto::-webkit-scrollbar {
    width: 4px;
  }

  .overflow-y-auto::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 2px;
  }

  .overflow-y-auto::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 2px;
  }

  .overflow-y-auto::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
  }
}
</style>